package com.gsi.webstore.platform.storefront.pipelet.orderprocess;

import java.util.Iterator;
import java.util.Map;

import com.intershop.beehive.core.capi.pipeline.Pipelet;
import com.intershop.beehive.core.capi.pipeline.PipeletExecutionException;
import com.intershop.beehive.core.capi.pipeline.PipelineDictionary;
import com.intershop.sellside.appbase.b2c.capi.basket.PLISplitInfo;
import com.intershop.sellside.appbase.b2c.capi.basket.ShippingPLISplitInfoConstants;

/**
 * This pipelet sets the store address id as the shiptoaddress ID in the split
 * product line item.It takes in input the iterator of the split product line
 * items and a map with key as line item uuid and value as store address id.
 */
public class SetStoreAddressIDInPLISplitInfos extends Pipelet
{

    /**
     * Constant used to access the pipeline dictionary with key 'PLISplitInfoIterator'
     * 
     * Iterator of the split product line items.
     */
    public static final String DN_PLI_SPLIT_INFO_ITERATOR = "PLISplitInfoIterator";
    /**
     * Constant used to access the pipeline dictionary with key 'StoreAddressIDMap'
     * 
     * A map with key as product line item uuid and value as store address ID
     */
    public static final String DN_STORE_ADDRESS_IDMAP = "StoreAddressIDMap";

    /**
     * The pipelet's execute method is called whenever the pipelets gets
     * executed in the context of a pipeline and a request. The pipeline
     * dictionary valid for the currently executing thread is provided as a
     * parameter.
     * 
     * @param dict
     *            The pipeline dictionary to be used.
     * @throws PipeletExecutionException
     *             Thrown in case of severe errors that make the pipelet execute
     *             impossible (e.g. missing required input data).
     */
    public int execute(PipelineDictionary dict)
    {        
        // lookup 'StoreAddressIDMap' in pipeline dictionary
        Map storeAddressIDMap = (Map)dict.get(DN_STORE_ADDRESS_IDMAP);
        
        // lookup 'SplitLineItemsIterator' in pipeline dictionary
        Iterator pLISplitInfoIterator = (Iterator)dict.get(DN_PLI_SPLIT_INFO_ITERATOR);
        
        if(pLISplitInfoIterator != null)
        {
            while(pLISplitInfoIterator.hasNext())
            {
                PLISplitInfo pLISplitInfo = (PLISplitInfo)pLISplitInfoIterator.next();
                if (storeAddressIDMap != null && storeAddressIDMap.containsKey(pLISplitInfo.getID()))
                {
                    String shipToAddressID=(String)storeAddressIDMap.get(pLISplitInfo.getID());
                    pLISplitInfo.set(ShippingPLISplitInfoConstants.SHIP_TO_ADDRESS_ID, shipToAddressID);
                } 
            }
        }

        return PIPELET_NEXT;
    }
}